package com.xzone.material.security.authentication

import com.fasterxml.jackson.databind.ObjectMapper
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.springframework.http.MediaType
import org.springframework.security.authentication.AuthenticationServiceException
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.Authentication
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter

class JsonUsernamePasswordAuthenticationFilter : UsernamePasswordAuthenticationFilter() {
    override fun attemptAuthentication(request: HttpServletRequest, response: HttpServletResponse): Authentication {
        if (request.method != "POST") {
            throw AuthenticationServiceException("Authentication method not supported: " + request.method)
        }

        if (request.contentType == MediaType.APPLICATION_JSON_VALUE || request.contentType == MediaType.APPLICATION_JSON_UTF8.type) {
            val mapper = ObjectMapper()
            val inputStream = request.inputStream
            val authenticationMap = mapper.readValue(inputStream, Map::class.java)
            val authRequest = UsernamePasswordAuthenticationToken.unauthenticated(
                authenticationMap["username"], authenticationMap["password"]
            )
            this.setDetails(request, authRequest)
            return authenticationManager.authenticate(authRequest)
        } else {
            return super.attemptAuthentication(request, response)
        }
    }
}